import {useDispatch, useSelector} from 'react-redux'
import {selectPosition, setAddressComponent} from '@/store/reducers'
import {useEffect, useMemo} from 'react'
import Taro from '@tarojs/taro'
import CityInfo from '@/type/position'
import {parseAddress} from '@/uitls/uitl'
import QQMapWX from '@/assets/lib/qqmap-wx-jssdk'
import config from '@/config'
import {updateUserInfo} from '@/services/user'

const QQMapSDK = new QQMapWX({
  key: config.qqMapKey || ''
})

export const usePositionHook = () => {
  const {position} = useSelector(selectPosition)
  const dispatch = useDispatch()
  useEffect(() => {
    Taro.getLocation({
      type: 'wgs84',
      success: res => {
        QQMapSDK.reverseGeocoder({
          location: res.latitude + ',' + res.longitude,
          success: ({result}: { result: CityInfo }) => {
            let userInfo = Taro.getStorageSync('userInfo') || {}
            userInfo.province = result.address_component.city
            Taro.setStorageSync('userInfo', userInfo)
            userInfo.avatarUrl && updateUserInfo(userInfo)
            dispatch(setAddressComponent(result.address_component))
          }
        })
      }
    })
  }, [dispatch])
  const curCity = useMemo((): string => {
    return parseAddress(position.address_component.city)
  }, [position.address_component.city])
  return {
    curCity
  }
}
